import React, { useState, useMemo } from 'react';
import s from './style.module.css';
import Breadcrumb, { Item } from '../../../../components/Breadcrumb';
import Helper from '../../../../components/Helper';
import { withRouter } from 'react-router';
import cn from 'classnames'
import SecurityRating from './SecurityRating';
import { IconS, Download } from './SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../../components/Label';
import Select from '@knownsec/react-component/dist/Select';
import fetchFer from 'API/fetch';
import Message from '@knownsec/react-component/dist/Message'
import Dialog from '@knownsec/react-component/dist/Dialog';
import Progress from '@knownsec/react-component/dist/Progress';
import Button from '@knownsec/react-component/dist/Button';
import { turnToUrlparam, GetQueryString } from '../../../../helpers/getUrlParams';
import { datetime } from '../../../../../common/formatter';
import moment from 'moment'
import AviliableTaskDetail from './AviliableTaskDetail';
import CollectFrequency from '../../../../components/CollectFrequency';
import { FREQ_UNIT_MAP } from '../../../../../common/constants';
const infoObj = {
	target_url: '资产地址',
	target_ip: '响应IP',
	url_count: '已扫描URL数',
	waf_info: '防御信息',
	result: '监测结果'
};
const taskMap = {
	vul: 'Web漏洞',
	ssl: 'SSL安全威胁',
	security_event: '安全事件',
	content: '内容违规'
}
function Detail({
	match: {
		params: { assetType },
	},
	location,
}) {
	const atid = GetQueryString(location.search, 'id');
	const type = GetQueryString(location.search, 'type');
	const jid = GetQueryString(location.search, 'jid');
	const [selVal, setSelVal] = useState([]);
	const [timeOpt, setTimeOpt] = useState([]);
	const [manualT, setManualT] = useState();
	const [detail, setDetail] = useState([{}]);
	const [overview, setOverview] = useState(null)
	const getHostDetail = async () => {
		const sendData = {
			asset_task_id: atid
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(
			`/api/v2/tasks/available/result?${params}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			setDetail(res?.data);
		} else {
			Message.show({ type: res.status, message: res.message })
		}
	};
	const resDemo = e => {
		const aa = e && e.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	const [isDownload, setIsDownload] = React.useState(true)
	const [downloadTaskId, setDownloadTaskId] = React.useState('')
	const [progressVisible, setProgressVisible] = React.useState(false)
	const [downloadPercent, setDownloadPercent] = React.useState(0)
	const downloadTimer = React.useRef()

	const downloadReport = () => {
		if (!isDownload) return false
		setIsDownload(false)
		fetchFer(
			`/api/v2/report/download_task`,
			{
				method: 'POST',
				body: JSON.stringify({
					download_type: "0",
					job_ids: jid,
					report_type: "latest"
				})
			}
		).then(res => {
			if (res.code === 200) {
				setIsDownload(true)
				setProgressVisible(true)
				setDownloadTaskId(res.result.download_task_id)
				downloadTimer.current = setInterval(() => {
					getProgress(
						res.result.download_task_id,
						[overview.job_name],
						0
					);
				}, 1000);
			} else {
				setIsDownload(true)
			}
		}).catch(e => {
			setIsDownload(true)
			return {}
		});
	}
	const getProgress = (id, name, type) => {
		fetchFer(`/api/v2/report/download_progress?download_task_id=${id}`)
			.then(res => {
				if (res.code === 200) {
					if (res.result.progress === 100) {
						setDownloadPercent(99);
						clearInterval(downloadTimer.current);
						fetch(`/api/v2/report/download_completed?download_task_id=${id}`)
							.then(res => {
								if (res.ok) {
									return res.blob();
								}
							})
							.then(blob => {
								const url = (window.webkitURL || window.URL).createObjectURL(
									blob
								);
								const a = document.createElement('a');
								if (type === 0) {
									a.download = `[${
										name[0] +
										(name.length > 1 ? '等多个资产' : '') +
										(name.length > 1 && type === 0 ? '汇总' : '')
									}]ScanV安全监测报告.docx`;
								} else {
									a.download = `[${
										name[0] +
										(name.length > 1 ? '等多个资产' : '') +
										(name.length > 1 && type === 0 ? '汇总' : '')
									}]ScanV安全监测报告.zip`;
								}
								a.href = url;
								setDownloadPercent(100);
								setTimeout(function () {
									setProgressVisible(false);
									a.click();
								}, 500);
							})
							.catch(error => {
								return {};
							});
					} else {
						setDownloadPercent(res.result.progress);
					}
				}
			})
			.catch(error => {
				setProgressVisible(false);
				clearInterval(timer.current);
				setDownloadPercent(0);
				Message.show({
					type: 'error',
					message: error.message,
				});
			});
	};
	React.useEffect(() => {
		getHostDetail();
	}, []);
	return (
		<div className={s.taskMain}>
			<Breadcrumb>
				<Item key="job-manage" disabled>
					任务管理
				</Item>
				<Item key="aviliable-task">可用性监测</Item>
				<Item key="">监测结果</Item>
			</Breadcrumb>
			{/* <div className={s.timeType}>
				{jid && <div className={cn(s.primaryColor, s.subVam)} onClick={downloadReport}>
					<svg width="14px" height="14px" viewBox="0 0 14 14" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
						<g id="资产" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
							<g id="监测任务管理-Web安全监测详情-漏洞" transform="translate(-1337.000000, -101.000000)" fill="#0B6FD6" fill-rule="nonzero">
								<g id="编组-6" transform="translate(227.000000, 97.000000)">
									<g id="编组-5" transform="translate(1110.000000, 0.000000)">
										<g id="218下载、导入" transform="translate(0.000000, 4.000000)">
											<path d="M3.64583333,8.16666667 L6.41666667,8.16666667 L6.41666667,0 L7.58333333,0 L7.58333333,8.16666667 L10.3541667,8.16666667 L7,11.6666667 L3.64583333,8.16666667 Z M14,7 L12.8333333,7 L12.8333333,12.8333333 L1.16666667,12.8333333 L1.16666667,7 L0,7 L0,14 L14,14 L14,7 Z" id="形状"></path>
										</g>
									</g>
								</g>
							</g>
						</g>
					</svg>
					<span className={cn(s.pr_t_1, s.ml8, s.cp)}>下载报告</span>
				</div>}
			</div> */}
			<div className={s.content}>
				<div className={s.header}>
					<div className={cn(s.df, s.jcsb, s.aifs)}>
						<div className={cn(s.fs20, s.fw, s.df, s.aic)}>
							<svg width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"><g id="资产画像1期-设计稿" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g id="HTTP监测-监测详情" transform="translate(-265.000000, -202.000000)"><g id="编组-15" transform="translate(250.000000, 184.000000)"><g id="编组-16" transform="translate(15.000000, 18.000000)"><g id="logo" fill="#A18EDD"><rect id="Rectangle-2" x="0" y="0" width="28" height="28" rx="4"></rect></g><g id="任务" transform="translate(5.000000, 5.000000)" fill="#FFFFFF" fill-rule="nonzero"><path d="M15.42825,0 L2.57174999,0 C1.15141935,0 0,1.15141935 0,2.57174999 L0,15.42825 C0,16.8485806 1.15141935,18 2.57174999,18 L15.42825,18 C16.8485806,18 18,16.8485806 18,15.42825 L18,2.57174999 C18,1.15141935 16.8485806,0 15.42825,0 Z M16.7153237,15.4317339 C16.7155934,15.7725477 16.5802062,16.0994551 16.339051,16.3402835 C16.0978958,16.5811119 15.7708051,16.7160556 15.429992,16.7153256 L2.5747258,16.7153256 C2.23091129,16.7153256 1.90625805,16.5832258 1.66311291,16.3400806 C1.41996778,16.0969355 1.28467742,15.7755484 1.28467742,15.4317339 L1.28467742,2.57298387 C1.28595804,1.86132295 1.86306379,1.28499645 2.5747258,1.28467742 L15.429992,1.28467742 C15.7712923,1.28502369 16.098471,1.42096178 16.3395278,1.66257661 C16.5805845,1.90419143 16.7157656,2.23168361 16.7153237,2.57298387 L16.7153237,15.4317339 Z" id="形状"></path><path d="M14.368947,5.23549604 L9.31581701,5.23549604 C8.96729607,5.23549604 8.68476402,5.51325752 8.68476402,5.85589366 C8.68476402,6.1985298 8.96729607,6.47629127 9.31581701,6.47629127 L14.368947,6.47629127 C14.717468,6.47629127 15,6.1985298 15,5.85589366 C15,5.51325752 14.717468,5.23549604 14.368947,5.23549604 L14.368947,5.23549604 Z M14.368947,10.2056871 L9.31581701,10.2056871 C8.96729607,10.2056871 8.68476402,10.4834486 8.68476402,10.8260847 C8.68476402,11.1687208 8.96729607,11.4464823 9.31581701,11.4464823 L14.368947,11.4464823 C14.717468,11.4464823 15,11.1687208 15,10.8260847 C15,10.4834486 14.717468,10.2056871 14.368947,10.2056871 Z M5.52600516,8.65371165 C4.30504242,8.65371165 3.31553708,9.62678954 3.31553708,10.8268558 C3.31553708,12.0269221 4.30532764,13 5.52600516,13 C6.74668267,13 7.73647322,12.0269221 7.73647322,10.8268558 C7.73647322,9.62678952 6.74696788,8.65371165 5.52600516,8.65371165 Z M6.19677526,11.4865803 C5.87671939,11.8009298 5.37537312,11.8492556 4.99930818,11.6020066 C4.62324324,11.3547576 4.47718473,10.8807868 4.65044699,10.4699259 C4.82370924,10.059065 5.26804287,9.82572893 5.71173919,9.91260199 C6.15543551,9.99947505 6.47493572,10.3823652 6.4748694,10.8271362 C6.4755024,11.0746685 6.37536207,11.3121589 6.19677526,11.4866504 L6.19677526,11.4865803 Z M6.9747174,4.17871708 L4.89431042,6.22392614 L4.0772929,5.42063392 C3.83084725,5.17834952 3.4312799,5.17834951 3.18483424,5.42063391 C2.93838859,5.66291831 2.93838858,6.05573894 3.18483423,6.29802335 L4.44808108,7.54001031 C4.56642708,7.65636194 4.72694109,7.72172793 4.89431042,7.72172793 C5.06167975,7.72172793 5.22219375,7.65636194 5.34053975,7.54001031 L7.86710475,5.0561065 C8.1106958,4.81336543 8.1093598,4.42285249 7.86411337,4.1817278 C7.61886694,3.94060311 7.22164702,3.93925847 6.9747174,4.17871708 L6.9747174,4.17871708 Z" id="形状"></path></g></g></g></g></g></svg>
							<span className={s.ml10}>任务名称：{detail?.name}</span>
						</div>
						{/* <div>最新一次监测结果：{moment(detail?.end_time).format('YYYY-MM-DD HH:mm:ss')}</div> */}
					</div>
					<div className={cn(s.df, s.jcsb, s.p0_40, s.aifs, s.mt20)}>
						<div>监测目标：{detail?.target}</div>
						<div>源站IP：{detail?.source_ip || '- -'}</div>
						<div>监测类型：{detail?.task_type === 'http' ? 'HTTP' : 'Ping'}</div>
						<div>监测频率：<CollectFrequency
							viewmode
							value={detail?.task_settings?.interval}
							unitMap={FREQ_UNIT_MAP}
						/>1次</div>
					</div>
				</div>
				<div className={s.infoBody}>
					<AviliableTaskDetail isHistory={false} taskType={type} data={detail} jid={jid} tid={selVal} atid={atid} />
				</div>
			</div>
			<Dialog
				title="提示"
				className={s.w400}
				maskClosable={false}
				visible={progressVisible}
				confirmText=""
				cancelText=""
				onhide={() => {
					setProgressVisible(false);
					clearInterval(downloadTimer.current);
					setDownloadPercent(0);
				}}
			>
				<div className={cn(s.p24, s.tac)}>
					<p>正在导出报告，请稍等···</p>
					<p>进度：{downloadPercent}%</p>
					<Progress percent={downloadPercent + '%'}></Progress>
				</div>
			</Dialog>
		</div>
	);
}
Detail.propTypes = {
	location: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
			jid: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
